Module Imports¶

In [1]:
import os
import pandas as pd

import numpy as np

import matplotlib.pyplot as plt
import seaborn as sns

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Rescaling, Conv2D, MaxPooling2D, Dense, Flatten, Dropout, BatchNormalization
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam

from sklearn.metrics import confusion_matrix, precision_score, recall_score, accuracy_score, f1_score

Data import and formatting¶

In [2]:
# location path of the datasets
train_dir = "/Users/preslav/Downloads/cw_cop528/imageset/train"
test_dir = "/Users/preslav/Downloads/cw_cop528/imageset/val"
In [3]:
# setting a common standard for the pixel values, to fall in 
# setting a validation and training split, alongside augmentation
# details about the train dataset
train_data = ImageDataGenerator(rescale=1./255,
                               rotation_range=40,
                               shear_range=0.2,
                               zoom_range=0.3,
                               horizontal_flip=True,
                               fill_mode="nearest",
                               width_shift_range=0.3,
                               height_shift_range=0.3,
                               validation_split=0.2)
val_data = ImageDataGenerator(rescale=1/255, 
                              validation_split=0.2)
test_data = ImageDataGenerator(rescale=1./255)
In [4]:
# importing the data batches and setting their properties 
train_batches = train_data.flow_from_directory(directory = train_dir, 
                                               target_size = (224, 224), 
                                               subset = "training",
                                               batch_size = 32, 
                                               seed = 2)
validation_batches = val_data.flow_from_directory(directory = train_dir, 
                                                  target_size = (224, 224), 
                                                  subset = "validation",
                                                  batch_size = 32, 
                                                  seed = 2)
test_batches = test_data.flow_from_directory(directory = test_dir, 
                                             target_size = (224, 224),
                                             batch_size = 32, 
                                             shuffle = False)
Found 7578 images belonging to 10 classes.
Found 1891 images belonging to 10 classes.
Found 3925 images belonging to 10 classes.
In [5]:
# import of the class labels names and their total number 
class_names = list(train_batches.class_indices.keys())
num_classes = len(class_names)
print(class_names)
print(num_classes)
['building', 'dog', 'fish', 'gas_station', 'golf', 'musician', 'parachute', 'radio', 'saw', 'vehicle']
10

Visualizing few "distored" images¶

In [6]:
# importing a batch of images and labels
img, lbl = next(train_batches)
In [7]:
# plotting 9 images and their respective class labels
plt.figure(figsize = (12, 12))
for i in range(9):
    class_index = np.argmax(lbl[i])
    plt.subplot(3, 3, i + 1)
    plt.imshow(img[i])
    plt.title(class_names[class_index])
    plt.axis("off")
plt.tight_layout()
plt.show()

Building Model Architecture¶

In [8]:
# setting the model's architecture
model_augmented = Sequential([
    Conv2D(16, (3,3), 1, activation = "relu"),
    MaxPooling2D(),
    Conv2D(32, (3,3), 1, activation = "relu"),
    Conv2D(32, (3,3), 1, activation = "relu"),
    MaxPooling2D(),
    Conv2D(32, (3,3), 1, activation = "relu"),
    Conv2D(32, (3,3), 1, activation = "relu"),
    MaxPooling2D(),
    Flatten(),
    Dense(256, activation = "relu"),
    Dense(num_classes, activation = "softmax")
])
Metal device set to: Apple M2
2023-03-17 11:25:11.992845: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:305] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
2023-03-17 11:25:11.992949: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:271] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>)
In [9]:
# setting the model's loss function, gradient descnet optimizer and evaluation metrics 
model_augmented.compile(optimizer = "adam", loss = "categorical_crossentropy", metrics = ["accuracy"])
In [10]:
# performing training of the model with the training batches and validaiton batches
epochs = 20
history_augmented= model_augmented.fit(train_batches,
                      validation_data = validation_batches,
                      epochs = epochs)
Epoch 1/20
2023-03-17 11:25:12.523623: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz
2023-03-17 11:25:12.806194: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:113] Plugin optimizer for device_type GPU is enabled.
237/237 [==============================] - ETA: 0s - loss: 2.1250 - accuracy: 0.2292
2023-03-17 11:25:59.261994: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:113] Plugin optimizer for device_type GPU is enabled.
237/237 [==============================] - 50s 210ms/step - loss: 2.1250 - accuracy: 0.2292 - val_loss: 1.8182 - val_accuracy: 0.3406
Epoch 2/20
237/237 [==============================] - 50s 211ms/step - loss: 1.8170 - accuracy: 0.3638 - val_loss: 2.0248 - val_accuracy: 0.3670
Epoch 3/20
237/237 [==============================] - 50s 209ms/step - loss: 1.6995 - accuracy: 0.4045 - val_loss: 1.6463 - val_accuracy: 0.4320
Epoch 4/20
237/237 [==============================] - 50s 209ms/step - loss: 1.6431 - accuracy: 0.4322 - val_loss: 1.5727 - val_accuracy: 0.4691
Epoch 5/20
237/237 [==============================] - 50s 210ms/step - loss: 1.5672 - accuracy: 0.4609 - val_loss: 1.5256 - val_accuracy: 0.4944
Epoch 6/20
237/237 [==============================] - 50s 210ms/step - loss: 1.4737 - accuracy: 0.5022 - val_loss: 1.4293 - val_accuracy: 0.5272
Epoch 7/20
237/237 [==============================] - 49s 208ms/step - loss: 1.4653 - accuracy: 0.5020 - val_loss: 1.4503 - val_accuracy: 0.5256
Epoch 8/20
237/237 [==============================] - 50s 210ms/step - loss: 1.4199 - accuracy: 0.5158 - val_loss: 1.4762 - val_accuracy: 0.5098
Epoch 9/20
237/237 [==============================] - 50s 209ms/step - loss: 1.3802 - accuracy: 0.5376 - val_loss: 1.3611 - val_accuracy: 0.5537
Epoch 10/20
237/237 [==============================] - 50s 210ms/step - loss: 1.3417 - accuracy: 0.5554 - val_loss: 1.3528 - val_accuracy: 0.5568
Epoch 11/20
237/237 [==============================] - 50s 209ms/step - loss: 1.3090 - accuracy: 0.5657 - val_loss: 1.3023 - val_accuracy: 0.5701
Epoch 12/20
237/237 [==============================] - 50s 209ms/step - loss: 1.2693 - accuracy: 0.5760 - val_loss: 1.1719 - val_accuracy: 0.6192
Epoch 13/20
237/237 [==============================] - 50s 209ms/step - loss: 1.2389 - accuracy: 0.5839 - val_loss: 1.1137 - val_accuracy: 0.6335
Epoch 14/20
237/237 [==============================] - 50s 209ms/step - loss: 1.2220 - accuracy: 0.5911 - val_loss: 1.1868 - val_accuracy: 0.6177
Epoch 15/20
237/237 [==============================] - 50s 209ms/step - loss: 1.2137 - accuracy: 0.5912 - val_loss: 1.1256 - val_accuracy: 0.6177
Epoch 16/20
237/237 [==============================] - 50s 209ms/step - loss: 1.1934 - accuracy: 0.6016 - val_loss: 1.2430 - val_accuracy: 0.6118
Epoch 17/20
237/237 [==============================] - 50s 210ms/step - loss: 1.1758 - accuracy: 0.6077 - val_loss: 1.1372 - val_accuracy: 0.6383
Epoch 18/20
237/237 [==============================] - 50s 210ms/step - loss: 1.1381 - accuracy: 0.6145 - val_loss: 1.1034 - val_accuracy: 0.6489
Epoch 19/20
237/237 [==============================] - 50s 209ms/step - loss: 1.1223 - accuracy: 0.6355 - val_loss: 1.0963 - val_accuracy: 0.6372
Epoch 20/20
237/237 [==============================] - 50s 209ms/step - loss: 1.1240 - accuracy: 0.6309 - val_loss: 1.0692 - val_accuracy: 0.6515
In [11]:
# getting model's summary
model_augmented.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 conv2d (Conv2D)             (None, None, None, 16)    448       
                                                                 
 max_pooling2d (MaxPooling2D  (None, None, None, 16)   0         
 )                                                               
                                                                 
 conv2d_1 (Conv2D)           (None, None, None, 32)    4640      
                                                                 
 conv2d_2 (Conv2D)           (None, None, None, 32)    9248      
                                                                 
 max_pooling2d_1 (MaxPooling  (None, None, None, 32)   0         
 2D)                                                             
                                                                 
 conv2d_3 (Conv2D)           (None, None, None, 32)    9248      
                                                                 
 conv2d_4 (Conv2D)           (None, None, None, 32)    9248      
                                                                 
 max_pooling2d_2 (MaxPooling  (None, None, None, 32)   0         
 2D)                                                             
                                                                 
 flatten (Flatten)           (None, None)              0         
                                                                 
 dense (Dense)               (None, 256)               4718848   
                                                                 
 dense_1 (Dense)             (None, 10)                2570      
                                                                 
=================================================================
Total params: 4,754,250
Trainable params: 4,754,250
Non-trainable params: 0
_________________________________________________________________

Evaluating Performance¶

Graphical evaluation¶

In [12]:
# Graphical evaluation of training performance 
acc = history_augmented.history['accuracy']
val_acc = history_augmented.history['val_accuracy']

loss = history_augmented.history['loss']
val_loss = history_augmented.history['val_loss']

epochs_range = range(epochs)

plt.figure(figsize=(11, 8))
plt.subplots_adjust(hspace = .3)
plt.subplot(2, 1, 1)
plt.plot(epochs_range, acc, label = 'Training Accuracy', color = "orange")
plt.plot(epochs_range, val_acc, label = 'Validation Accuracy', color = "blue")
plt.legend(loc = 'best')
plt.xlabel('Epochs')
plt.title('Training and Validation Accuracy', size = 13)

plt.subplot(2, 1, 2)
plt.plot(epochs_range, loss, label = 'Training Loss', color = "orange")
plt.plot(epochs_range, val_loss, label = 'Validation Loss', color = "blue")
plt.legend(loc = 'best')
plt.title('Training and Validation Loss', size = 13)
plt.xlabel('Epochs')

plt.suptitle("Base Model with Data Augmentation", size=15)
plt.show()

Evaluating model's performance on the test dataset¶

In [13]:
# Test loss and accuracy measurments 
test_loss, test_acc = model_augmented.evaluate(test_batches)
print('Test loss:', test_loss)
print('Test accuracy:', test_acc)
123/123 [==============================] - 7s 57ms/step - loss: 1.0504 - accuracy: 0.6642
Test loss: 1.0504111051559448
Test accuracy: 0.6642038822174072

Evaluating the classification performance¶

i) via confussion matrix¶

In [14]:
# getting prediction labales by running the softmax results in argmax
test_labels = test_batches.classes
y_pred = model_augmented.predict(test_batches)
predicted_lables = np.argmax(y_pred, axis = 1)
cm =  confusion_matrix(test_labels, predicted_lables)
  2/123 [..............................] - ETA: 7s 
2023-03-17 11:41:54.307492: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:113] Plugin optimizer for device_type GPU is enabled.
123/123 [==============================] - 7s 56ms/step
In [15]:
# dataframe containing the confussion matrix
cfm = pd.DataFrame(cm, index = class_names, columns = class_names)
In [16]:
# plotting the conffusion matrix
sns.heatmap(cfm, annot=True, fmt='d', cmap='Purples')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.xticks(rotation=78)
plt.title('Base Model with Augmentation', size = 15)
plt.show()

ii) via designated classification performance evaluators¶

In [17]:
print("Preicision score:", precision_score(test_labels, predicted_lables, average="weighted"))
print("Recall score:", recall_score(test_labels, predicted_lables, average = "weighted"))
print("F1_score:", f1_score(test_labels, predicted_lables, average = "weighted"))
Preicision score: 0.6947771548506045
Recall score: 0.664203821656051
F1_score: 0.6675302072358554

Testing the model's prediction onto actual images¶

In [18]:
# importing the test datest again, so that this time images can be shuffled
# so that displayed images are not ordered in the same way as in the dataset 
# and variety of classes can be examined 
test_data_shuffled = tf.keras.utils.image_dataset_from_directory(test_dir, shuffle = True, seed = 247)
Found 3925 files belonging to 10 classes.
In [19]:
def right_format_image(pic):
    '''
    This function returns a 
    reshaped image into 224x224 
    format in terms of height and 
    width.
    Further it normalizes the 
    pixel values within the range
    of [0, 1].
    '''
    img_size = (224, 224)
    image = tf.image.resize(pic, img_size)
    image_expanded = np.expand_dims(image, axis=0)
    image_copy = np.copy(image_expanded)
    normalized = image_copy/255.
    return normalized
In [20]:
def data_iterator(data):
    '''
    This function returns as arrays the 
    components of a batch.
    '''
    iterator = data.as_numpy_iterator()
    batch = iterator.next()
    return batch
In [21]:
# plotting images from the test dataset, with their actual and predicted from the model labels 
predicted_batch = data_iterator(test_data_shuffled)

plt.figure(figsize=(12, 12))
plt.subplots_adjust(hspace = .1, wspace=.3)
plt.suptitle("Base Model with Data Augmentation", size = 20)
for i in range(9):
    image, label = predicted_batch[0][i], predicted_batch[1][i]
    predictions = model_augmented.predict(right_format_image(image))
    prediction_label = class_names[predictions.argmax()]
    ax = plt.subplot(3, 3, i + 1)
    plt.imshow(image.astype(np.uint8))
    plt.title("Actual label:{};\nPredicted label:{}".format(class_names[label],
                                                           class_names[predictions.argmax()]), size = 9)
    plt.axis("off")
1/1 [==============================] - 0s 66ms/step
1/1 [==============================] - 0s 7ms/step
1/1 [==============================] - 0s 7ms/step
1/1 [==============================] - 0s 7ms/step
1/1 [==============================] - 0s 7ms/step
1/1 [==============================] - 0s 7ms/step
2023-03-17 11:42:01.807644: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:113] Plugin optimizer for device_type GPU is enabled.
1/1 [==============================] - 0s 7ms/step
1/1 [==============================] - 0s 7ms/step
1/1 [==============================] - 0s 8ms/step
In [ ]: